const Controller = require('egg').Controller
const fs = require('fs')
const path = require('path')
/**
 * @Controller 下载资料
 */
class downloadController extends Controller {

  /**
   * @summary 添加下载资料
 */
  async insert() {
    const { ctx, service } = this
    const body = ctx.request.body
    ctx.validate({
      title: 'string',
    },body)

    await service.downloadService.insert(body)
    ctx.body = {
      code: 200,
      message: '添加成功'
    }
  }

  /**
   * @summary 删除下载资料
 */
  async delete() {
    const { ctx,service } = this
    const body = ctx.request.body
    ctx.validate({
      id: 'string'
    },body)
    const data = await service.downloadService.delete(body.id)

    ctx.body = data
  }

  /**
   * @summary 修改下载资料
 */
   async update() {
    const { ctx,service } = this
    const body = ctx.request.body
    ctx.validate({
      id: 'string',
      title: 'string',
    },body)
    const data = await service.downloadService.update(body)
    
    ctx.body = data
  }

  /**
  * @summary 获取下载资料列表
 */
  async list() {
    const { ctx,service } = this
    const body = ctx.request.query
    ctx.validate({
      pageNum: 'string'
    },body)
    const data = await service.downloadService.getList(body)
    ctx.body = {
      code: 200,
      data
    }
  }

  /**
   *@summary down下载
   */
  async downFile() {
    const { ctx } = this
    const _url = ctx.request.body.url
    const relativePath = _url.split(this.config.imgDomain)[1]
    const filePath = path.join(process.cwd(), '/app' + relativePath)
    ctx.body = fs.createReadStream(filePath)
  }
}

module.exports = downloadController